﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour {

	public float moveSpeed = 3;
	private Vector3 bulletEulerAngles;
	private float timeVal;

	private float defendTimeVal = 5;
	private bool isDefended = true;

	private SpriteRenderer sr;
	/*
	 * 坦克资源数组
	 * 上右下左
	 * */
	public Sprite[] tankSprite;

	public GameObject bulletPrefab;
	public GameObject explosionPrefab;
	public GameObject defendEffectPrefab;

	public AudioSource moveAudio;
	public AudioClip[] audioClip;//0走,1停

	private void Awake() {
		sr = GetComponent<SpriteRenderer>();
	}

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
		//保护是否处于无敌状态
		if (isDefended)
		{
			defendEffectPrefab.SetActive(true);
			defendTimeVal -= Time.deltaTime;
			if (defendTimeVal <= 0)
			{
				isDefended = false;
				defendEffectPrefab.SetActive(false);
			}
		}
	}

	private void FixedUpdate() {
		if (PlayerManager.Instance.isDefeat)
		{
			return;
		}
		Move();
		//攻击的CD
		if (timeVal > 0.4)
		{
			Attack();
		}
		else
		{
			timeVal += Time.fixedDeltaTime;
		}

	}

	private void Attack() {
		if (Input.GetKeyDown(KeyCode.Space)) {
			//子弹产生的角度=坦克当前角度+子弹应该旋转角度
			Instantiate(bulletPrefab, transform.position, Quaternion.Euler(transform.eulerAngles + bulletEulerAngles));
			timeVal = 0;
		}
	}

	//坦克移动方法
	private void Move() {
		//垂直方向移动
		float v = Input.GetAxisRaw("Vertical");
		transform.Translate(Vector3.up * v * moveSpeed * Time.deltaTime, Space.World);
		if (v < 0)
		{
			sr.sprite = tankSprite[2];
			bulletEulerAngles = new Vector3(0, 0, -180);
		}
		else if (v > 0)
		{
			sr.sprite = tankSprite[0];
			bulletEulerAngles = new Vector3(0, 0, 0);
		}

		if (Mathf.Abs(v) > 0.05) {
			moveAudio.clip = audioClip[0];
			if (!moveAudio.isPlaying) {
				moveAudio.Play();
			}
		}
		/*else
		{
			moveAudio.clip = audioClip[1];
			if (!moveAudio.isPlaying)
			{
				moveAudio.Play();
			}
		}*/

		if (v != 0)
		{
			return;
		}
		/*
		 * Input.GetAxisRaw("Horizontal");这是Unity自带的函数,直接引用
		 */
		//水平方向移动
		float h = Input.GetAxisRaw("Horizontal");
		transform.Translate(Vector3.right * h * moveSpeed * Time.deltaTime, Space.World);
		if (h < 0)
		{
			sr.sprite = tankSprite[3];
			bulletEulerAngles = new Vector3(0, 0, 90);
		}
		else if (h > 0)
		{
			sr.sprite = tankSprite[1];
			bulletEulerAngles = new Vector3(0, 0, -90);
		}

		if (Mathf.Abs(h) > 0.05)
		{
			moveAudio.clip = audioClip[0];
			if (!moveAudio.isPlaying)
			{
				moveAudio.Play();
			}
		}
		else {
			moveAudio.clip = audioClip[1];
			if (!moveAudio.isPlaying)
			{
				moveAudio.Play();
			}
		}
	}

	//坦克销毁方法
	private void Die() {
		if (isDefended) {
			return;
		}
		PlayerManager.Instance.isDead = true;
		Instantiate(explosionPrefab, transform.position,transform.rotation);
		Destroy(gameObject);
	}

}
